package com.lanbu.web.controller.system;

import com.lanbu.system.domain.PptContext;

import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;

@RestController
@RequestMapping("/system/count")
public class pptController {


    @PostMapping("/list")
    public ResponseEntity<String> list(@RequestBody PptContext pptContext, HttpServletRequest request) {
    try {
        String content = pptContext.getContent();

        // 创建 Word 文档
        XWPFDocument doc = new XWPFDocument();
        for (String line : content.split("\n")) {
            line = line.trim();
            if (line.isEmpty()) continue;

            XWPFParagraph paragraph = doc.createParagraph();
            XWPFRun run = paragraph.createRun();

            if (line.startsWith("###")) {
                paragraph.setStyle("Heading3");
                run.setBold(true);
                run.setFontSize(14);
                run.setText(line.replaceFirst("^###\\s*", ""));
            } else if (line.startsWith("-")) {
                paragraph.setStyle("ListBullet");
                run.setText("• " + line.replaceFirst("^-\\s*", ""));
                run.setFontSize(12);
            } else {
                run.setText(line);
                run.setFontSize(12);
            }
        }

        // 保存到临时目录
        String fileName = "word的生成-" + System.currentTimeMillis() + ".docx";
        String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

        try (FileOutputStream out = new FileOutputStream(filePath)) {
            doc.write(out);
        }
        doc.close();

        // 构造可下载链接（根据你实际部署的路径配置）
        String downloadUrl = request.getScheme() + "://" + request.getServerName() +
                ":" + request.getServerPort() + "/system/count/download/" + URLEncoder.encode(fileName, "UTF-8");
        System.out.println(downloadUrl);
        return ResponseEntity.ok(downloadUrl);

    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating document");
    }
}
    @GetMapping("/download/{fileName}")
    public void downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        try {
            String fullPath = System.getProperty("java.io.tmpdir") + File.separator + fileName;
            File file = new File(fullPath);

            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                 BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {

                byte[] buffer = new byte[4096];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("Error downloading document");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }




//@PostMapping("/pptlist")
//public ResponseEntity<String> pptlist(@RequestBody PptContext pptContext, HttpServletRequest request) {
//    try {
//        String content = pptContext.getContent();
//        String[] lines = content.split("\n");
//
//        XMLSlideShow ppt = new XMLSlideShow();
//        XSLFSlide slide = null;
//        XSLFTextShape contentBox = null;
//
//        for (String line : lines) {
//            line = line.trim();
//            if (line.isEmpty()) continue;
//
//            // 新建幻灯片并添加标题
//            if (line.startsWith("###")) {
//                slide = ppt.createSlide();
//                slide.getBackground().setFillColor(new Color(250, 250, 250));
//
//                // 标题
//                String titleText = line.replaceFirst("^###\\s*", "");
//                XSLFTextShape title = slide.createTextBox();
//                title.setAnchor(new Rectangle(50, 30, 620, 60));
//                XSLFTextParagraph titlePara = title.addNewTextParagraph();
//                titlePara.setTextAlign(TextAlign.CENTER);
//                XSLFTextRun titleRun = titlePara.addNewTextRun();
//                titleRun.setText(titleText);
//                titleRun.setFontSize(28.0);
//                titleRun.setBold(true);
//                titleRun.setFontFamily("微软雅黑");
//
//                // 内容框
//                contentBox = slide.createTextBox();
//                contentBox.setAnchor(new Rectangle(60, 100, 600, 400));
//            }
//            // 内容添加到当前幻灯片
//            else if (slide != null && contentBox != null) {
//                XSLFTextParagraph para = contentBox.addNewTextParagraph();
//                para.setLineSpacing(120.0);
//
//                if (line.startsWith("-")) {
//                    para.setBullet(true);
//                    line = line.replaceFirst("^-\\s*", "");
//                }
//
//                para.setTextAlign(TextAlign.LEFT);
//                XSLFTextRun run = para.addNewTextRun();
//                run.setText(line);
//                run.setFontSize(18.0);
//                run.setFontFamily("微软雅黑");
//            }
//        }
//
//        String fileName = "ppt的生成-" + System.currentTimeMillis() + ".pptx";
//        String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;
//
//        try (FileOutputStream out = new FileOutputStream(filePath)) {
//            ppt.write(out);
//        }
//        ppt.close();
//
//        String downloadUrl = request.getScheme() + "://" + request.getServerName() +
//                ":" + request.getServerPort() + "/system/count/pptdownload/" + URLEncoder.encode(fileName, "UTF-8");
//        return ResponseEntity.ok(downloadUrl);
//
//    } catch (Exception e) {
//        e.printStackTrace();
//        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating PPT");
//    }
//}
@PostMapping("/pptlist")
public ResponseEntity<String> pptlist(@RequestBody PptContext pptContext, HttpServletRequest request) {
    try {
        String content = pptContext.getContent();
        String[] lines = content.split("\n");

        XMLSlideShow ppt = new XMLSlideShow();
        XSLFSlide slide = null;
        XSLFTextShape contentBox = null;
        int slideIndex = 0;

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;

            // 标题行
            if (line.startsWith("###")) {
                slide = ppt.createSlide();
                slide.getBackground().setFillColor(new Color(250, 250, 250));
                slideIndex++;

                String titleText = line.replaceFirst("^###\\s*", "");
                XSLFTextShape title = slide.createTextBox();
                title.setAnchor(new Rectangle(50, 30, 620, 60));
                XSLFTextParagraph titlePara = title.addNewTextParagraph();
                titlePara.setTextAlign(TextAlign.CENTER);
                XSLFTextRun titleRun = titlePara.addNewTextRun();
                titleRun.setText(titleText);
                titleRun.setFontSize(28.0);
                titleRun.setBold(true);
                titleRun.setFontFamily("微软雅黑");

                contentBox = slide.createTextBox();
                contentBox.setAnchor(new Rectangle(60, 100, 600, 400));

                XSLFTextShape pageNumber = slide.createTextBox();
                pageNumber.setAnchor(new Rectangle(680, 500, 100, 30));
                XSLFTextParagraph pagePara = pageNumber.addNewTextParagraph();
                pagePara.setTextAlign(TextAlign.RIGHT);
                XSLFTextRun pageRun = pagePara.addNewTextRun();
                pageRun.setText("第 " + slideIndex + " 页");
                pageRun.setFontSize(12.0);
                pageRun.setFontFamily("微软雅黑");
            }
            // 普通内容行
            else {
                // 如果还没有创建任何幻灯片，创建默认页
                if (slide == null) {
                    slide = ppt.createSlide();
                    slide.getBackground().setFillColor(new Color(250, 250, 250));
                    slideIndex++;

                    // 默认标题
                    XSLFTextShape title = slide.createTextBox();
                    title.setAnchor(new Rectangle(50, 30, 620, 60));
                    XSLFTextParagraph titlePara = title.addNewTextParagraph();
                    titlePara.setTextAlign(TextAlign.CENTER);
                    XSLFTextRun titleRun = titlePara.addNewTextRun();
                    titleRun.setText("默认标题");
                    titleRun.setFontSize(28.0);
                    titleRun.setBold(true);
                    titleRun.setFontFamily("微软雅黑");

                    contentBox = slide.createTextBox();
                    contentBox.setAnchor(new Rectangle(60, 100, 600, 400));

                    XSLFTextShape pageNumber = slide.createTextBox();
                    pageNumber.setAnchor(new Rectangle(680, 500, 100, 30));
                    XSLFTextParagraph pagePara = pageNumber.addNewTextParagraph();
                    pagePara.setTextAlign(TextAlign.RIGHT);
                    XSLFTextRun pageRun = pagePara.addNewTextRun();
                    pageRun.setText("第 " + slideIndex + " 页");
                    pageRun.setFontSize(12.0);
                    pageRun.setFontFamily("微软雅黑");
                }

                XSLFTextParagraph para = contentBox.addNewTextParagraph();
                para.setLineSpacing(120.0);

                if (line.startsWith("-")) {
                    para.setBullet(true);
                    line = line.replaceFirst("^-\\s*", "");
                }

                para.setTextAlign(TextAlign.LEFT);

                Pattern pattern = Pattern.compile("\\*\\*(.*?)\\*\\*");
                Matcher matcher = pattern.matcher(line);
                int lastIndex = 0;

                while (matcher.find()) {
                    if (matcher.start() > lastIndex) {
                        String normalText = line.substring(lastIndex, matcher.start());
                        XSLFTextRun run = para.addNewTextRun();
                        run.setText(normalText);
                        run.setFontSize(18.0);
                        run.setFontFamily("微软雅黑");
                    }

                    String boldText = matcher.group(1);
                    XSLFTextRun boldRun = para.addNewTextRun();
                    boldRun.setText(boldText);
                    boldRun.setFontSize(20.0);
                    boldRun.setBold(true);
                    boldRun.setFontFamily("微软雅黑");

                    lastIndex = matcher.end();
                }

                if (lastIndex < line.length()) {
                    String remaining = line.substring(lastIndex);
                    XSLFTextRun run = para.addNewTextRun();
                    run.setText(remaining);
                    run.setFontSize(18.0);
                    run.setFontFamily("微软雅黑");
                }
            }
        }

        String fileName = "ppt的生成-" + System.currentTimeMillis() + ".pptx";
        String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

        try (FileOutputStream out = new FileOutputStream(filePath)) {
            ppt.write(out);
        }
        ppt.close();

        String downloadUrl = request.getScheme() + "://" + request.getServerName() +
                ":" + request.getServerPort() + "/system/count/pptdownload/" + URLEncoder.encode(fileName, "UTF-8");
        return ResponseEntity.ok(downloadUrl);

    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating PPT");
    }
}


    @GetMapping("/pptdownload/{fileName}")
    public void pptdownloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        try {
            String fullPath = System.getProperty("java.io.tmpdir") + File.separator + fileName;
            File file = new File(fullPath);

            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.presentationml.presentation");

            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                 BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {

                byte[] buffer = new byte[4096];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("Error downloading document");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


}
